﻿
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEditorInternal;
using UnityEngine;

//[ToolButton("Hierarchy","删除空引用")]
public class DeletNullComponent : IToolsButtonEvent
{
    public void Run()
    {
        if (Selection.activeTransform == null)
            return;
#if UNITY_5 || UNITY_2017
        GameObject ab = AssetDatabase.LoadAssetAtPath<GameObject>(AssetDatabase.GetAssetPath(Selection.activeGameObject));
#else
        var ab = PrefabUtility.GetCorrespondingObjectFromSource(Selection.activeGameObject);
#endif
        if (ab != null)
        {
            UpdatePrefab(ab);
        }
        else
        {
            UpdateHierarchy(Selection.activeGameObject);
        }

        var array = GameObject.FindObjectsOfType<GameObject>();
        foreach (var item in array)
        {
            Debug.LogError(item);
        }

    }

    /// <summary>
    /// 闪退
    /// </summary>
    /// <param name="go"></param>
    static void UpdateHierarchy(GameObject go)
    {
        UpdateGameObject(go);
        EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene());
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

    }
    static void UpdateGameObject(GameObject go)
    {

        //var array = go.transform.TransformChilds();
        //foreach( var item in array)
        //{
        //    ComponentUtility.DestroyComponentsMatching();
        //}
        //foreach (var item in array)
        //{
        //    var monos = item.GetComponents<Component>();

        //    var so = new SerializedObject(item.gameObject);
        //    var com = so.FindProperty("m_Component");

        //    for (int i = monos.Length - 1; i >= 0; i--)
        //    {
        //        if (monos[i] == null)
        //        {
        //            Debug.LogError(i);
        //            com.DeleteArrayElementAtIndex(i);
        //        }
        //    }
        //    so.ApplyModifiedProperties();
        //}
    }
   

    static void UpdatePrefab(GameObject go)
    {
        string path = string.Empty;
        if (go != null)
        {
            path = AssetDatabase.GetAssetPath(go);
            if (path == null)
                return;
        }

        UpdateGameObject(go);

        EditorUtility.SetDirty(go);
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

    }

   
}
